package router

import (
	"embed"
	"io/fs"
	"net/http"
	"palworld/handler"
	"palworld/middleware"

	"github.com/gin-gonic/gin"
	//_ "palworld/statik"
)

//go:embed static
var f embed.FS

type Router struct {
	engine *gin.Engine
	web    *gin.Engine
}

func NewRouter() *Router {
	r := gin.New()
	r.Use(middleware.Cors())
	w := gin.Default()
	w.Use(middleware.Cors())
	return &Router{
		engine: r,
		web:    w,
	}
}

func (r *Router) Run() {
	r.addHandlers()
	go r.web.Run(":8000")
	r.engine.Run(":8090")
}

func (r *Router) addHandlers() {
	st, _ := fs.Sub(f, "static")
	r.web.StaticFS("/", http.FS(st))
	r.web.NoRoute(func(c *gin.Context) {
		data, err := f.ReadFile("static/index.html")
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.HTML(http.StatusOK, "text/html; charset=utf-8", data)
	})
	r.engine.POST("/api/v1/login", handler.Login)
	router := r.engine.Group("/api/v1")
	router.Use(middleware.Auth())
	router.GET("/config", handler.GetConfig)
	router.POST("/config", handler.SetConfig)
	router.POST("/start", handler.StartGame)
	router.POST("/stop", handler.StopGame)
	router.POST("/restart", handler.RestartGame)
	router.GET("/running", handler.IsRunning)
	router.PUT("/user", handler.ResetPassword)
	router.GET("/mem", handler.GetMem)
	router.POST("/update", handler.Update)
	router.GET("/cpu", handler.GetCpu)
	router.GET("/yaml", handler.GetYamlConfig)
	router.POST("/yaml", handler.UpdateConfig)
	router.GET("/players", handler.GetPlayers)
	router.GET("/ban", handler.Ban)
	router.GET("/kick", handler.Kick)
	router.POST("/msg", handler.Broadcast)
	router.GET("/bak", handler.GetBaks)
	router.DELETE("/bak/:name", handler.DelBak)
}
